package com.szh.shenzhihaodemo.Utils;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

public class DBOpenHelper extends SQLiteOpenHelper {
    private String CREATE_USER = "create table user(_id integer primary key autoincrement,name varchar(20)," +
            "password text)";

    private String CREATE_TEMP_USER = "alter table user rename to _temp_user";//把表名改为临时表名

    private String INSERT_DATA = "insert into user select * from _temp_user";

    private String DROP_USER = "drop table _temp_user";
    private String INSERT_USER="alter table user add column sex text";
    public DBOpenHelper(@Nullable Context context) {//第一次创建时调用的函数，创建users数据库，版本号为1
        super(context, "users", null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "create table user(_id integer primary key autoincrement,name varchar(20)," +
                "password text)";

        db.execSQL(sql);  //执行建user表语句,创建数据表 id为组件， 包含 name，password，sex信息
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


                db.execSQL(CREATE_TEMP_USER);//改名
                db.execSQL(CREATE_USER);//创建user
                db.execSQL(INSERT_DATA);//复制
                //删除临时表
                db.execSQL(DROP_USER);//删除原来的表
                //插入列
                //ALTER   TABLE   tablename   ADD   columnname   VARCHAR(20)
                db.execSQL(INSERT_USER);


    }
}
